#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#define POLL_INTERVAL	10	
#define PROC_FILE		"/proc/batterymine/batt"
#define DATA_DIR		"/data/batterymine/"
#define MAX_FILE_PATH	80
#define TX_BUF_SIZE		100


/*	-- TODO --
	sys/resource.h - include to be able to change process priority
	setpriority(PRIO_PROCESS,0,-20);
 */



int openHandles(FILE **infile, FILE **outfile, time_t epoch);
int closeHandles(FILE *infile, FILE *outfile);

int main(int arc, char **argv) {
	printf("Battery Monitor Daemon Starting...\n");
	
	pid_t pid, sid;
	pid = fork();
	if (pid < 0) exit(EXIT_FAILURE);
	else if (pid > 0) {
		// Parent process
		printf("Daemon spawned - pid: %d\n", pid);
		exit(EXIT_SUCCESS);
	}

	// Child process continues here
	umask(0);
	sid = setsid();
	if (sid < 0) exit(EXIT_FAILURE);

	
	time_t epoch;						// Timestamp to be used as file name
	FILE *proc_file;					// Handle for procfs file
	FILE *data_file;					// Handle for persistent file
	char tx_buff[TX_BUF_SIZE];			// Transfer buffer
	int numr, numw;						// Track data read and written

	/* MAIN PROCESSING LOOP */
	while(1) {
		epoch = time(NULL);
		openHandles(&proc_file, &data_file, epoch);

		while(feof(proc_file)==0){
			numr = fread(tx_buff,1,TX_BUF_SIZE,proc_file);
			if(numr!=100 && ferror(proc_file)!=0) {
				printf("Error reading PROCFS\n");
				closeHandles(proc_file, data_file);
				exit(EXIT_FAILURE);
			}
			numw = fwrite(tx_buff,1,numr,data_file);
			if(numw != numr) {
				printf("Error writing data file\n");
				closeHandles(proc_file, data_file);
				exit(EXIT_FAILURE);
			}
		}
		
		closeHandles(proc_file, data_file);
		sleep(POLL_INTERVAL);
	}
}

int openHandles(FILE **infile, FILE **outfile, time_t epoch) {
	char fname_buffer[MAX_FILE_PATH];	// Buffer stores name of output file
	sprintf(fname_buffer, "%s%lu", DATA_DIR, epoch);
	
	*outfile = fopen(fname_buffer, "w");
	if(*outfile == NULL) {
		printf("couldn't open data file\n");
		closeHandles(*infile, *outfile);
		exit(EXIT_FAILURE);
	}
	
	*infile = fopen(PROC_FILE, "r");
	if(*infile == NULL) {
		printf("Couldn't open procfs file\n");
		closeHandles(*infile, *outfile);
		exit(EXIT_FAILURE);
	}
}

int closeHandles(FILE *infile, FILE *outfile) {
	if(&infile != NULL) fclose(infile);
	if(&outfile != NULL) fclose(outfile);
}